<?php
session_start();

// 数据库配置
define('DB_HOST', 'localhost');
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
define('API_KEY', '123');//API密钥 不用动

// 自动获取网站URL
function get_current_url() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $script = $_SERVER['SCRIPT_NAME'];
    // 移除脚本文件名，获取目录路径
    $path = preg_replace('/\/[a-zA-Z0-9_]+\.php$/', '', $script);
    // 移除 admin 或 pay 目录（如果存在）
    $path = preg_replace('/\/admin$/', '', $path);
    $path = preg_replace('/\/pay$/', '', $path);
    return rtrim($protocol . $host . $path, '/');
}

// 网站URL，末尾不带斜杠
define('SITE_URL', get_current_url());

// 创建PDO实例
try {
    $pdo = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// 获取系统设置
function getSettings() {
    global $pdo;
    $settings = [];
    $stmt = $pdo->query("SELECT name, value FROM settings");
    while ($row = $stmt->fetch()) {
        $settings[$row['name']] = $row['value'];
    }
    return $settings;
}

// 安全过滤函数
function sanitize($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

// 检查自动登录
if (!isset($_SESSION['admin_id']) && isset($_COOKIE['admin_remember'])) {
    list($admin_id, $token) = explode('|', $_COOKIE['admin_remember']);
    
    if ($admin_id && $token) {
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
        $stmt->execute([$admin_id]);
        $admin = $stmt->fetch();
        
        if ($admin && $token === md5($admin['password'] . $_SERVER['HTTP_USER_AGENT'])) {
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_username'] = $admin['username'];
            
            // 更新cookie有效期
            $expire = time() + 60 * 60 * 24 * 5; // 5天
            setcookie('admin_remember', $admin['id'] . '|' . $token, $expire, '/');
        }
    }
}